View Javadoc
1   package edu.jiangxin.encode;
2   
3   import java.io.File;
4   import java.io.IOException;
5   
6   import org.junit.jupiter.api.Test;
7   
8   import edu.jiangxin.apktoolbox.file.core.EncoderConvert;
9   import edu.jiangxin.apktoolbox.file.core.EncoderDetector;
10  
11  import static org.junit.jupiter.api.Assertions.assertEquals;
12  import static org.junit.jupiter.api.Assertions.assertTrue;
13  
14  /**
15   * @author jiangxin
16   * @author 2018-09-09
17   *
18   */
19  public class EncoderConvertTest {
20  
21      // 测试文件如果太小可能无法准确判断编码
22      // GB2312、GBK、GB18030的关系可以参考: <https://www.zhihu.com/question/19677619>
23      String path = EncoderConvertTest.class.getResource("/EncoderConvertTest").getPath();
24  
25      @Test
26      public void testDetectEncode01() {
27          assertTrue(new File(path, "UTF-8.txt").exists());
28          assertEquals("UTF-8", EncoderDetector.judgeFile(path + File.separator + "UTF-8.txt"));
29      }
30  
31      @Test
32      public void testDetectEncode02() {
33          assertTrue(new File(path, "GB2312.txt").exists());
34          String encode = EncoderDetector.judgeFile(path + File.separator + "GB2312.txt");
35          assertTrue("GB2312".equals(encode) || "GBK".equals(encode) || "GB18030".equals(encode));
36      }
37  
38      @Test
39      public void testEncodeFile() throws IOException {
40          EncoderConvert.encodeFile(path + File.separator + "UTF-8.txt", "UTF-8",
41                  path + File.separator + "UTF-8_TO_GB2312.txt", "GBK");
42          assertTrue(new File(path, "UTF-8_TO_GB2312.txt").exists());
43          String encode = EncoderDetector.judgeFile(path + File.separator + "UTF-8_TO_GB2312.txt");
44          assertTrue("GB2312".equals(encode) || "GBK".equals(encode) || "GB18030".equals(encode));
45      }
46  
47      @Test
48      public void testEncodeDir() throws IOException {
49          File srcDir = new File(path, "test");
50          assertTrue(srcDir.exists());
51          File[] srcFileList = srcDir.listFiles();
52          for (File f : srcFileList) {
53              assertEquals("UTF-8",
54                      EncoderDetector.judgeFile(path + File.separator + "test" + File.separator + f.getName()));
55          }
56  
57          EncoderConvert.encodeDir(path + File.separator + "test", "UTF-8", path + File.separator + "testResult",
58                  "GB2312");
59          File desDir = new File(path, "testResult");
60          assertTrue(desDir.exists());
61          File[] desFileList = desDir.listFiles();
62          for (File f : desFileList) {
63              String encode = EncoderDetector.judgeFile(desDir.getPath() + File.separator + f.getName());
64              assertTrue("GB2312".equals(encode) || "GBK".equals(encode) || "GB18030".equals(encode));
65          }
66      }
67  
68  }